package leetcode.p160;

/***
 * 160
 * Intersection of Two Linked Lists    两个链表交点
 * 两个指针，走的总路程相等，必定会在交点相遇
 */
public class Solution {
    public class  ListNode {
        int val;
        ListNode next;
        ListNode (int val) {
            this.val = val;
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) {
            return null;
        }
        ListNode p = headA , q = headB;

        while (p != null && q != null && p != q) {
            p = p.next;
            q = q.next;

            if(p == q) return p;
            if (p == null) {
                p = headB;
            }
            if (q == null) {
                q = headA;
            }
        }
        return p;
    }

}
